<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

function otx_script_execute($file, $vars = array())
{
	foreach (array_keys($GLOBALS) as $key) {
		if (substr($key, 0, 2) == '_X') {
			global $$key;
		}
	}

	extract((array) $vars);
	unset($file, $vars, $key);
	return include(func_get_arg(0));
}

function otx_script_content($file, $vars = array())
{
	$obLevel = ob_get_level();
	ob_start();

	try {
		otx_script_execute($file, $vars);
	} catch (Exception $e) {
		$curObLevel = ob_get_level();
		if ($curObLevel > $obLevel) {
			do {
				ob_get_clean();
				$curObLevel = ob_get_level();
			} while ($curObLevel > $obLevel);
		}

		throw $e;
	}

	return ob_get_clean();
}

function otx_script_controller($file)
{
	$obLevel = ob_get_level();
	ob_start();

	try {
		include_once $file;

		$class_name = otx_router_module()
				. '_controller_'
				. otx_router_controller();
		if (!class_exists($class_name)) {
			throw new Exception('Controller class not exists: ' . $class_name);
		}

		$instance = new $class_name();
		$instance->module_name = otx_router_module();
		$instance->controller_name = otx_router_controller();
		$instance->action_name = otx_router_action();

		$method_name = otx_router_action();
		if (!method_exists($instance, $method_name)) {
			$method_name .= '_action';
			if (!method_exists($instance, $method_name)) {
				throw new Exception('Controller method not exists: ' . $method_name);
			}
		}

		otx_event_dispatch('router_dispatch_before');
		$instance->$method_name();
		otx_event_dispatch('router_dispatch_after');
	} catch (Exception $e) {
		$curObLevel = ob_get_level();
		if ($curObLevel > $obLevel) {
			do {
				ob_get_clean();
				$curObLevel = ob_get_level();
			} while ($curObLevel > $obLevel);
		}

		throw $e;
	}

	return ob_get_clean();
}